package com.example.speeddating.config;

import com.example.speeddating.entity.TokenEntity;
import com.example.speeddating.annotaion.LoginUser;
import com.example.speeddating.tool.StringTools;
import com.example.speeddating.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Method;

@Slf4j
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver
{

    @Autowired
    private TokenBlacklistService tokenBlacklistService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class)&&parameter.getParameterType().isAssignableFrom(TokenEntity.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        Method method = parameter.getMethod();
        String methodName = method.getName();
        //得到使用这个注解的方法名字
//        log.info("methodName:{}",methodName);
        // header中获取用户token
        String token = request.getHeader("Authorization");
        if (StringTools.isEmpty(token) && ((methodName.equals("recommendList")||methodName.equals("articleDetail")))){
            return null;
        }
        if (methodName.equalsIgnoreCase("logout") || methodName.equalsIgnoreCase("logOff")){
            tokenBlacklistService.addToBlacklist(token);
        }
        Long userId = (Long.valueOf(JwtTokenUtil.getUserIdByToken(token)));
        String userName = JwtTokenUtil.getUserName(token);
        // TODO 根据userId获取User信息，这里省略，直接创建一个User对象。
        TokenEntity user = new TokenEntity();
        user.setNickname(userName);
        user.setId(userId);
        log.info(user.toString());
        return user;
    }
}
